/*
@file 用户行为跟踪
@author <AA>
@version 20160520
 */
 
(function() {
  
  //主函数
  (function(definition, undef) {
    var $, exports, global, i,ipaddress;
    global = this;
    $ = global.jQuery;
    exports = {};
    
    definition(global, exports, $);
    
    for (i in exports) {
      global[i] =  exports[i];
    }
  })
  
  //子函数定义
  (function(global, exports, $, undef,ipaddress) {
    var iarr = [], _key=0;
    var ads, crossdomainGet, domReadyListener, done, findAllAds, linksContent, protocol, ref, s, trackingAd, viewedHeight, cookieId;
    protocol = global.location.protocol.substr(0, 4) === 'http' ? '' : 'http:';
    ref = global.document.referrer || '-';
    ads = [];
    viewedHeight = 0;
    
    //监听页面
    domReadyListener = function() {
      var ad, groups, k, n, v, w, _i, _len, _ref, _ref1;
      n = 0;
      //滚动页
      w = $(global).scroll(function() {
        if (!ads[0]) {
          return;
        }
        global.clearTimeout(n);
        return n = global.setTimeout(function() {
          var ad, top, _i, _len;
          top = w.scrollTop() + w.height();
          if (top > viewedHeight) {
            viewedHeight = top;
            for (_i = 0, _len = ads.length; _i < _len; _i++) {
              ad = ads[_i];
              if (!(!ad.viewed && top >= ad.top)) {
                continue;
              }
              ad.viewed = true;
              crossdomainGet(ad.data());
            }
          }
        }, 2000);
      });
      groups = {};
      _ref = $('.tracking-ad');
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        ad = _ref[_i];
        k = $(ad).attr('data-mod');
        ((_ref1 = groups[k]) != null ? _ref1.push(ad) : void 0) || (groups[k] = [ad]);
      }
      for (k in groups) {
        v = groups[k];
        trackingAd($(v));
      }
      return w.triggerHandler('scroll');
    };

  //时间格式整理
  function date2str(dtime,dtype) { 
    var z = {M:dtime.getMonth()+1,d:dtime.getDate(),h:dtime.getHours(),m:dtime.getMinutes(),s:dtime.getSeconds()}; 
    dtype = dtype.replace(/(M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)}); 
    dtype = dtype.replace(/y+/g,dtime.getFullYear());
    return dtype;
  }

    /*
     跟踪指定的推广位，包括曝光和点击
     @param {CSS Selector/jQuery Object/DOMElement/DOMElement[]} ele 包含推广链接的推广位容器标签
     */
     
    //数据跟踪
    trackingAd = exports.trackingAd = function(ele) {
      var filter, mod, pid, _ref, curl, dtime;

      if (typeof ele === 'string' || !ele instanceof $) {
        ele = $(ele);
      }
    mod = ele.attr('data-mod');
    
    //取得当前URL
    curl = global.location.href;
    if(typeof(curl)==="undefined"){
    curl="-";
    }

    //取得当前时间
      dtime = date2str(new Date(),"yyyy-MM-dd hh:mm:ss");
    if(typeof(dtime)==="undefined"){
    dtime="-";
    }
  
      filter = ele.attr('data-filter') || '';
      return findAllAds(ele, filter, function(links) {
        var ad, con, userName;
        con = linksContent(links);
    if(typeof(VCG)!="undefined"){
      userName = VCG.userName;
    }else{
      userName = "-";
    }
        ad = {
          top: ele.offset().top,
          ele: ele,
          viewed: false,
          data: function() {
            var _ref1;
            return {
        dtime: dtime,
              userId: ((_ref1 = /(; )?(userId)=([^;]+)/.exec(global.document.cookie)) != null ? _ref1[3] : void 0) || '-',
              user_name: userName,
              ref: ref,
        mod: mod,
              con: encodeURIComponent(con),
              ck: '-',
              useragent: global.navigator.userAgent,
              cid: cookieId(),
        ipaddress:ipaddress,
        curl: curl
            };
          }
        };
        ads.push(ad);
        if (viewedHeight > ad.top) {
          $(global).triggerHandler('scroll');
        }
       
        //曝光点击
        return links.click(function() {
          var d;
          if (this.href && this.innerHTML.replace(/^\s+|\s+$/g, '')) {
            d = ad.data();
            d.ck = encodeURIComponent(linksContent($(this)));
            crossdomainGet(d);
          }
        });
      });
    };
  //取得cookieId
    cookieId = function () {
    if (global.document.cookie.length > 0) {
        var c_name="cookie_id";
      c_start = global.document.cookie.indexOf(c_name + "=");
      if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        c_end = global.document.cookie.indexOf(";", c_start);
        if (c_end == -1) {
          c_end = global.document.cookie.length;
        }
        return unescape(global.document.cookie.substring(c_start, c_end));
      }
    }
    return "-";
   };

    //封装数据
    findAllAds = function(cont, filter, callback) {
      var count, iframes, links;
      links = $('a' + filter, cont);
      iframes = $('iframe', cont);
      if (iframes[0]) {
        count = iframes.length;
        return iframes.each(function() {
          var ifr, listener;
          ifr = $(this);
          listener = function() {
            if (ifr === null) {
              return;
            }
            links = links.add(ifr.contents().find('a' + filter));
            ifr = null;
            count--;
            if (count === 0) {
              return callback(links);
            }
          };
          return ifr.load(listener);
        });
      } else {
        return callback(links);
      }
    };
    
    //连接数据
    linksContent = function(ele) {
      return ele.map(function() {
        var text;
        text = this.innerHTML.replace(/<[^>]+>/g, '').replace(/^\s+|\s+$/g, '') || this.title || this.alt || this.innerHTML.replace(/^\s+|\s+$/g, '');
        return text + ',' + this.href;
      }).get().join(';');
    };
    
    //提交数据
    crossdomainGet = function(parmData) {
      if (!parmData.con) {
        return;
      }
      parmData[Math.random() * 10000 | 0] = '';
      parmData['x-acl-token'] = 'QQToken';
    var sendData = ((function() {
          var results;
          results = [];
          for (p in parmData) {
            results.push(encodeURIComponent(p) + ':' + encodeURIComponent(parmData[p]));
          }
          return results;
        })()).join('#');
      var dataJson = [],headersObj = {};
    var headObj = {};
    headObj.comp="vcg_designer_user_profile";
    headObj.pv="re";
    headersObj.headers = headObj;
      headersObj.body = sendData;
      dataJson.push(headersObj);
    
      $.ajax({  
            url : "https://track-vcg-community.csdn.net",  
            type : 'POST',  
            data : JSON.stringify(dataJson),  
            dataType : 'json',  
            success : function(data, status, xhr) {  
    
            },  
            Error : function(xhr, error, exception) {  

                alert(exception.toString());
        }  
       }); 
    };
  
    ipaddress = returnCitySN["cip"];
    if ($ === undef) {
      done = false;
      s = document.createElement('script');
      s.type = 'text/javascript';
      s.charset = 'utf-8';
      s.src = 'https://csdnimg.cn/www/js/jquery-1.4.2.min.js';
      s.onload = s.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) {
          done = true;
          global.jQuery.noConflict();
          $ = global.jQuery;
          $(domReadyListener);
          return s.onload = s.onreadystatechange = null;
        }
      };
      document.getElementsByTagName('head')[0].insertBefore(s, null);
    } else {
      $(domReadyListener);
    }
  });

}).call(this);
